#include "GetUserId.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QNetworkRequest>
#include <QNetworkReply>


GetUserId::GetUserId()
    : QObject(Q_NULLPTR)
{
    m_manager = NULL;
//    m_manager = new QNetworkAccessManager;
//    QObject::connect(m_manager,
//                     SIGNAL(finished(QNetworkReply*)),
//                     this,
//                     SLOT(onReplyFinished(QNetworkReply*)),
//                     Qt::QueuedConnection);
//    m_manager->moveToThread(m_mainThread);
}

void GetUserId::handleSession()
{

    /*
    code = request.args.get("code")
    # code = code.encode('ascii')
    print("getUseID, code: ", code)
    wxAppid = "wx47d3e60f1d949404"
    wxspSecret = "df1f19ce614d3bf196c8f25762c5cb30"
    grant_type = "authorization_code"
    params = "appid="+wxAppid+"&secret="+wxspSecret+"&js_code="+code+"&grant_type="+grant_type
    hostWx = 'https://api.weixin.qq.com/sns/jscode2session?' + params
    print("hoswx: ", hostWx)
    r = requests.get(hostWx)
    result = r.text
    return result
    */

    QMap<QString, QString> mapQuery = m_session->requestUrlQuery();

    QString strAppId = "wx47d3e60f1d949404";
    QString strSecret = "df1f19ce614d3bf196c8f25762c5cb30";
    QString strCode = mapQuery.value("code");
    QString strGrantType = "authorization_code";

    QString strUrl = QString("https://api.weixin.qq.com/sns/jscode2session?appid=%1&secret=%2&js_code=%3&grant_type=%4")
            .arg(strAppId)
            .arg(strSecret)
            .arg(strCode)
            .arg(strGrantType);


    qDebug() << "strUrl in GetUserId: " << strUrl;

    QNetworkRequest req;
    req.setUrl(QUrl(strUrl));

    QSslConfiguration sslConfig = req.sslConfiguration();
    sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
    sslConfig.setProtocol(QSsl::TlsV1SslV3);
    req.setSslConfiguration(sslConfig);

    QMetaObject::invokeMethod(this,
                              "onGet",
                              Qt::QueuedConnection,
                              Q_ARG(QNetworkRequest, req));
}

void GetUserId::onReplyFinished(QNetworkReply *reply)
{
    QByteArray bytes = reply->readAll();
    QJsonParseError jsonError;
    QJsonDocument document = QJsonDocument::fromJson(bytes,&jsonError);
    if(jsonError.error != QJsonParseError::NoError){
        qDebug()<<QStringLiteral("resolve Json failed");
        return;
    }

    // parse json
    if (document.isObject()){
        QJsonObject obj = document.object();
        m_session->replyJsonObject(obj);
    }

    reply->deleteLater();
}

void GetUserId::onGet(const QNetworkRequest &req)
{
    if (NULL == m_manager)
    {
        m_manager = new QNetworkAccessManager;
        QObject::connect(m_manager,
                         SIGNAL(finished(QNetworkReply*)),
                         this,
                         SLOT(onReplyFinished(QNetworkReply*)),
                         Qt::QueuedConnection);
        m_manager->moveToThread(s_mainThread);
    }

    m_manager->get(req);
}
